//
//  TryCollectionViewC.m
//  PlanDemo
//
//  Created by 在成长开发 on 2025/9/8.
//

#import "TryCollectionViewC.h"
#import "CellModel.h"
#import "PlanCell.h"
#import "WeekPlanLayout.h"

@interface TryCollectionViewC ()<WeekPlanLayoutDelegate, UICollectionViewDataSource, UICollectionViewDragDelegate, UICollectionViewDropDelegate>

@property (nonatomic, strong) UICollectionView * collectionView;

@property (nonatomic, strong) NSMutableArray <CellModel *>* dataSource;

@property (nonatomic, strong) NSIndexPath * dragPassIndexPath;

@end

@implementation TryCollectionViewC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"十五周保教计划还原";
    
    self.dataSource = [CellModel fifteenWeek];

    [self.view addSubview:self.collectionView];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.collectionView.frame = CGRectMake(0, self.view.safeAreaInsets.top, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds) - self.view.safeAreaInsets.top - self.view.safeAreaInsets.bottom);
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CellModel * model = self.dataSource[indexPath.item];
    return CGSizeMake((kSingleColWidth + kItemSpace) * model.useCol - kItemSpace, (kSingleRowWidth + kLineSpace) * model.useRow - kLineSpace);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout atRowForItemAtIndexPath:(NSIndexPath *)indexPath {
    CellModel * model = self.dataSource[indexPath.item];
    return model.row;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout atColForItemAtIndexPath:(NSIndexPath *)indexPath {
    CellModel * model = self.dataSource[indexPath.item];
    return model.col;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return kLineSpace;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return kItemSpace;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return [self.dataSource count];
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    PlanCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PlanCell" forIndexPath:indexPath];
    
    CellModel * model = self.dataSource[indexPath.item];
    
    cell.label.text = model.content;
    
    
    
    switch (model.type) {
        case CellType_Fixed: {
            cell.backgroundColor = [[UIColor purpleColor] colorWithAlphaComponent:0.1];
            cell.layer.borderWidth = 1;
            cell.layer.borderColor = [[UIColor purpleColor] colorWithAlphaComponent:0.3].CGColor;
        } break;
        case CellType_Text: {
            cell.backgroundColor = [[UIColor cyanColor] colorWithAlphaComponent:0.1];
            cell.layer.borderWidth = 1;
            cell.layer.borderColor = [[UIColor cyanColor] colorWithAlphaComponent:0.3].CGColor;
        } break;
        default: {
            cell.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.1];
            cell.layer.borderWidth = 1;
            cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
        } break;
    }
    
    if (self.dragPassIndexPath != nil) {
        if (indexPath.section == self.dragPassIndexPath.section && indexPath.item == self.dragPassIndexPath.item) {
            cell.backgroundColor = [[UIColor brownColor] colorWithAlphaComponent:0.2];
        }
    }
    
    return cell;
}

#pragma mark - UICollectionViewDragDelegate
- (NSArray<UIDragItem *> *)collectionView:(UICollectionView *)collectionView itemsForBeginningDragSession:(id<UIDragSession>)session atIndexPath:(NSIndexPath *)indexPath {
    CellModel * model = self.dataSource[indexPath.item];
    if (model.canDrag == NO) {
        return @[];
    }
    NSItemProvider * provider = [[NSItemProvider alloc] initWithObject:@""];
    UIDragItem * item = [[UIDragItem alloc] initWithItemProvider:provider];
    item.localObject = model;
    return @[item];
}

- (nullable UIDragPreviewParameters *)collectionView:(UICollectionView *)collectionView dragPreviewParametersForItemAtIndexPath:(NSIndexPath *)indexPath {
    UIDragPreviewParameters * params = [[UIDragPreviewParameters alloc] init];
    params.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.5];
    if (@available(iOS 14.0, *)) {
        params.shadowPath = [UIBezierPath bezierPath];
    }
    return params;
}

- (BOOL)collectionView:(UICollectionView *)collectionView dragSessionIsRestrictedToDraggingApplication:(id<UIDragSession>)session {
    return YES;
}

#pragma mark - UICollectionViewDropDelegate
- (nullable UIDragPreviewParameters *)collectionView:(UICollectionView *)collectionView dropPreviewParametersForItemAtIndexPath:(NSIndexPath *)indexPath {
    UIDragPreviewParameters * params = [[UIDragPreviewParameters alloc] init];
    params.backgroundColor = [UIColor clearColor];
    if (@available(iOS 14.0, *)) {
        params.shadowPath = [UIBezierPath bezierPath];
    }
    return params;
}

- (UICollectionViewDropProposal *)collectionView:(UICollectionView *)collectionView dropSessionDidUpdate:(id<UIDropSession>)session withDestinationIndexPath:(nullable NSIndexPath *)destinationIndexPath {
    NSMutableArray <NSIndexPath *>* needReloadIndexs = [NSMutableArray array];
    if (destinationIndexPath) {
        CellModel * targetModel = self.dataSource[destinationIndexPath.item];
        UIDragItem * dragItem = session.items.firstObject;
        CellModel * sourceModel = dragItem.localObject;
        if ([targetModel canDropFrom:sourceModel]) {
            if (self.dragPassIndexPath) {
                [needReloadIndexs addObject:self.dragPassIndexPath];
            }
            [needReloadIndexs addObject:destinationIndexPath];
            self.dragPassIndexPath = destinationIndexPath;
        }
    }
    
    if ([needReloadIndexs count] != 0) {
        [collectionView performBatchUpdates:^{
            [collectionView reloadItemsAtIndexPaths:needReloadIndexs];
        } completion:^(BOOL finished) {
            //
        }];
    }
    return [[UICollectionViewDropProposal alloc] initWithDropOperation:UIDropOperationMove intent:UICollectionViewDropIntentUnspecified];
}

- (void)collectionView:(UICollectionView *)collectionView performDropWithCoordinator:(id<UICollectionViewDropCoordinator>)coordinator {
    NSIndexPath * toIndexPath = coordinator.destinationIndexPath;
    if (toIndexPath == nil) {
        return;
    }
    
    if (coordinator.items.firstObject && coordinator.items.firstObject.sourceIndexPath) {
        UIDragItem * item = coordinator.items.firstObject.dragItem;
        CellModel * source = item.localObject;
        CellModel * to = self.dataSource[toIndexPath.item];
        if ([to canDropFrom:source] == NO) {
            return;
        }
        NSIndexPath * fromIndexPath = coordinator.items.firstObject.sourceIndexPath;
        [collectionView performBatchUpdates:^{
            NSString * content = self.dataSource[toIndexPath.item].content;
            self.dataSource[toIndexPath.item].content = self.dataSource[fromIndexPath.item].content;
            self.dataSource[fromIndexPath.item].content = content;
            
            [collectionView reloadItemsAtIndexPaths:@[fromIndexPath, toIndexPath]];
        } completion:^(BOOL finished) {
        }];
        [coordinator dropItem:item toItemAtIndexPath:toIndexPath];
    }
}

- (void)collectionView:(UICollectionView *)collectionView dropSessionDidExit:(id<UIDropSession>)session {
    [self _clearDragPass];
}

- (void)collectionView:(UICollectionView *)collectionView dropSessionDidEnd:(id<UIDropSession>)session {
    [self _clearDragPass];
}

- (void)_clearDragPass {
    if (self.dragPassIndexPath) {
        NSIndexPath * needReload = self.dragPassIndexPath;
        self.dragPassIndexPath = nil;
        [self.collectionView performBatchUpdates:^{
            [self.collectionView reloadItemsAtIndexPaths:@[needReload]];
        } completion:^(BOOL finished) {
            //
        }];
    }
}

#pragma mark - getter or setter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        WeekPlanLayout * layout = [[WeekPlanLayout alloc] init];
        layout.delegate = self;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 100, 100) collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.dragDelegate = self;
        _collectionView.dropDelegate = self;
        
        
        [_collectionView registerClass:[PlanCell class] forCellWithReuseIdentifier:@"PlanCell"];
        
        _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    return _collectionView;
}


@end
